import { ref, reactive, watch, unref } from 'vue';
import { Style, Fill, Stroke, Icon } from 'ol/style';
import { Draw, Select, Modify } from 'ol/interaction';
import { Circle as CircleStyle } from 'ol/style';
import Delete from 'ol-ext/interaction/Delete';
import { Feature } from 'ol';
import { Point, LineString, Polygon, Circle } from 'ol/geom';
import { ElMessage } from 'element-plus';

/**
 * 地图绘图工具钩子函数
 * @param {Object} map - OpenLayers地图实例或包含地图实例的ref对象
 * @param {Object} sourceFeatures - 矢量图层数据源或包含数据源的ref对象
 * @returns {Object} 绘图相关方法和状态
 */
export function useDraw(map, sourceFeatures) {
  console.log('useDraw被调用，参数:', {
    map: map ? '传入' : '未传入',
    mapType: typeof map,
    mapHasValue: map?.value !== undefined ? '有value属性' : '无value属性',
    sourceFeatures: sourceFeatures ? '传入' : '未传入',
    sourceFeaturesType: typeof sourceFeatures,
    sourceFeaturesHasValue: sourceFeatures?.value !== undefined ? '有value属性' : '无value属性'
  });
  
  // 确定实际使用的地图和数据源对象
  const actualMap = map?.value !== undefined ? map.value : map;
  const actualSourceFeatures = sourceFeatures?.value !== undefined ? sourceFeatures.value : sourceFeatures;
  
  console.log('使用以下对象:', {
    actualMap: actualMap ? '已获取' : '未获取',
    actualMapType: typeof actualMap,
    actualSourceFeatures: actualSourceFeatures ? '已获取' : '未获取',
    actualSourceFeaturesType: typeof actualSourceFeatures
  });
  
  // 如果参数完全不存在，直接中止
  if (!actualMap || !actualSourceFeatures) {
    console.error('useDraw参数错误:',
      !actualMap ? 'map参数为空' : '',
      !actualSourceFeatures ? 'sourceFeatures参数为空' : ''
    );
    throw new Error('绘图初始化失败：参数不完整');
  }
  
  // 降低验证严格性，允许组件初始化完成
  if (typeof actualMap.addInteraction !== 'function' || typeof actualSourceFeatures.addFeature !== 'function') {
    console.warn('useDraw参数类型警告:',
      typeof actualMap.addInteraction !== 'function' ? 'map不是有效的OpenLayers Map对象' : '',
      typeof actualSourceFeatures.addFeature !== 'function' ? 'sourceFeatures不是有效的VectorSource对象' : '',
      '如果使用了无效对象，部分功能可能不可用'
    );
  }
  
  // 状态
  const isDrawing = ref(false);
  const isIconDrawing = ref(false);
  const isDelete = ref(false);
  const isModify = ref(false);
  const selectedShape = ref('');
  const selectedIcon = ref('destination');
  const drawInstance = ref(null);
  const iconFeatureArr = ref([]);
  const scale = ref(0.1);
  
  // 交互实例
  const interactions = reactive({
    delete: null,
    modify: null,
    select: null
  });
  
  // 形状选项
  const shapeOptions = [
    { type: 'Polygon', icon: 'EditPen', name: '多边形' },
    { type: 'Circle', icon: 'EditPen', name: '圆形' },
    { type: 'LineString', icon: 'EditPen', name: '线段' },
    { type: 'Point', icon: 'EditPen', name: '点' }
  ];
  
  // 图标选项
  const iconOptions = [
    { type: 'destination', name: '目的地' },
    { type: 'icon', name: '图标' }
  ];
  
  /**
   * 验证地图对象和数据源是否已初始化
   * @returns {Boolean} 验证结果
   */
  function validateMapAndSource() {
    const mapInstance = unref(actualMap);
    const sourceFeaturesInstance = unref(actualSourceFeatures);
    
    if (!mapInstance || typeof mapInstance.addInteraction !== 'function') {
      console.error('地图对象未初始化或不可用');
      return false;
    }
    
    if (!sourceFeaturesInstance) {
      console.error('数据源未初始化或不可用');
      return false;
    }
    
    return true;
  }
  
  /**
   * 清除绘图交互
   */
  function clearDrawInteraction() {
    try {
      // 验证地图对象是否已初始化
      if (!validateMapAndSource()) {
        console.warn('无法清除绘图交互，地图对象未初始化');
        return;
      }
      
      const mapInstance = unref(actualMap);
      
      if (drawInstance.value) {
        mapInstance.removeInteraction(drawInstance.value);
        drawInstance.value = null;
        console.log('绘图交互已清除');
        
        // 重置绘制状态，确保UI显示与实际功能一致
        isDrawing.value = false;
      }
    } catch (error) {
      console.error('清除绘图交互失败:', error);
    }
  }
  
  /**
   * 绘制形状
   * @param {String} type - 形状类型
   * @param {String} fillColor - 填充颜色
   */
  function drawShape(type, fillColor = 'rgba(255, 0, 0, 0.5)') {
    try {
      // 验证地图对象和数据源是否已初始化
      if (!validateMapAndSource()) {
        ElMessage.error('地图对象或数据源未初始化，无法绘制');
        return;
      }
      
      const mapInstance = unref(actualMap);
      const sourceFeaturesInstance = unref(actualSourceFeatures);
      
      // 清除所有现有交互
      clearInteractions();
      
      // 重置所有状态
      isDrawing.value = true;
      isDelete.value = false;
      isModify.value = false;
      isIconDrawing.value = false; // 确保关闭图标绘制状态
      
      if (!type) return;
      
      console.log(`开始绘制${type}形状，地图状态:`, mapInstance ? '可用' : '不可用');
      
      // 创建绘图交互
      try {
        const draw = new Draw({
          source: sourceFeaturesInstance,
          type: type,
          stopClick: false // 允许点击事件继续传播
        });
        
        // 修复3D模式下的交互问题
        enable3DInteraction();
        
        // 监听开始绘制事件
        draw.on('drawstart', (evt) => {
          console.log('开始绘制', evt);
          isDrawing.value = true; // 确保状态正确
          
          // 添加一些额外的数据属性，辅助识别
          const feature = evt.feature;
          feature.set('drawTime', new Date().toISOString());
          feature.set('drawType', type);
        });
        
        // 监听结束绘制事件
        draw.on('drawend', (evt) => {
          console.log('结束绘制', evt);
          const feature = evt.feature;
          
          // 获取几何类型
          const geometryType = feature.getGeometry().getType();
          console.log('绘制的几何类型:', geometryType);
          
          // 检查是否处于3D模式
          const is3DMode = document.querySelector('.cesium-widget');
          
          // 根据几何类型设置不同样式
          if (geometryType === 'Point') {
            // 点颜色根据类型设置不同颜色
            let pointColor = 'rgba(255, 0, 0, 0.8)'; // 默认红色
            
            // 根据type参数设置不同颜色
            switch(type) {
              case 'Point-Red':
                pointColor = 'rgba(255, 0, 0, 0.8)'; // 红色
                break;
              case 'Point-Blue':
                pointColor = 'rgba(30, 144, 255, 0.8)'; // 蓝色
                break;
              case 'Point-Green':
                pointColor = 'rgba(0, 128, 0, 0.8)'; // 绿色
                break;
              case 'Point-Yellow':
                pointColor = 'rgba(255, 215, 0, 0.8)'; // 黄色
                break;
              default:
                // 使用默认红色
                break;
            }
            
            // 点类型使用圆形样式，增大尺寸和可见度
            feature.setStyle(
              new Style({
                image: new CircleStyle({
                  radius: is3DMode ? 5 : 7, // 3D模式下稍微减小半径
                  fill: new Fill({
                    color: pointColor
                  }),
                  stroke: new Stroke({
                    color: 'white',
                    width: is3DMode ? 1 : 2 // 3D模式下减小线宽
                  })
                })
              })
            );
          } else if (geometryType === 'LineString') {
            // 线类型样式
            feature.setStyle(
              new Style({
                stroke: new Stroke({
                  color: 'rgba(30, 144, 255, 0.8)', // 蓝色线条
                  width: is3DMode ? 1 : 3 // 3D模式下使用较小的线宽
                })
              })
            );
          } else if (geometryType === 'Polygon' || geometryType === 'Circle') {
            // 面类型样式
            feature.setStyle(
              new Style({
                fill: new Fill({
                  color: fillColor // 使用参数中的填充颜色
                }),
                stroke: new Stroke({
                  color: 'rgba(0, 0, 0, 0.8)',
                  width: is3DMode ? 1 : 2 // 3D模式下减小线宽
                })
              })
            );
          }
          
          // 添加Cesium兼容属性
          if (is3DMode) {
            feature.set('olcs_properties', {
              olcs_skip_style_conversion: true,
              olcs_custom_style: true
            });
          }
          
          // 绘制完成后，保持绘图状态，允许继续绘制
          isDrawing.value = true;
        });
        
        // 保存绘图交互实例
        drawInstance.value = draw;
        
        // 添加到地图
        mapInstance.addInteraction(draw);
        console.log('绘图交互已添加到地图');
      } catch (error) {
        console.error('创建绘图交互失败:', error);
        isDrawing.value = false;
        ElMessage.error('绘图工具初始化失败');
      }
    } catch (error) {
      console.error('绘制形状失败:', error);
      isDrawing.value = false;
      ElMessage.error('绘图操作失败');
    }
  }
  
  /**
   * 增强3D模式下的交互能力
   */
  function enable3DInteraction() {
    try {
      // 检查是否处于3D模式
      const is3DMode = document.querySelector('.cesium-widget');
      if (!is3DMode) return;
      
      console.log('检测到3D模式，启用特殊处理确保绘图工具可用');
      
      // 添加特殊样式，确保事件穿透
      if (!document.getElementById('draw-3d-fix-style')) {
        const style = document.createElement('style');
        style.id = 'draw-3d-fix-style';
        style.innerHTML = `
          .cesium-widget, .cesium-widget canvas {
            pointer-events: none !important;
          }
          .ol-viewport {
            z-index: 1000 !important;
            pointer-events: auto !important;
          }
          .draw-tools {
            z-index: 2000 !important;
            pointer-events: auto !important;
          }
          .draw-tools button {
            z-index: 2001 !important;
            pointer-events: auto !important;
            position: relative;
          }
          .ol-unselectable {
            pointer-events: auto !important;
          }
        `;
        document.head.appendChild(style);
      }
      
      // 确保绘图容器可点击
      setTimeout(() => {
        // 获取绘图工具容器
        const drawContainer = document.querySelector('.draw-tools');
        if (drawContainer) {
          drawContainer.style.zIndex = '2000';
          drawContainer.style.pointerEvents = 'auto';
          
          // 确保按钮可点击
          const buttons = drawContainer.querySelectorAll('button');
          buttons.forEach(btn => {
            btn.style.pointerEvents = 'auto';
            btn.style.position = 'relative';
            btn.style.zIndex = '2001';
          });
        }
        
        // 修复Cesium Canvas的事件穿透
        const cesiumCanvas = document.querySelector('.cesium-widget canvas');
        if (cesiumCanvas) {
          cesiumCanvas.style.pointerEvents = 'none';
        }
        
        // 确保OpenLayers视口可接收事件
        const olViewport = document.querySelector('.ol-viewport');
        if (olViewport) {
          olViewport.style.zIndex = '1000';
          olViewport.style.pointerEvents = 'auto';
        }
      }, 300);
    } catch (error) {
      console.error('增强3D模式交互能力失败:', error);
    }
  }
  
  /**
   * 绘制图标
   * @param {String} iconType - 图标类型
   */
  const addIcon = async (iconType) => {
    try {
      console.log('开始添加图标:', iconType)
      
      // 验证地图对象和数据源是否已初始化
      if (!validateMapAndSource()) {
        console.warn('无法添加图标，地图对象或数据源未初始化')
        return
      }
      
      const mapInstance = unref(actualMap)
      const sourceFeaturesInstance = unref(actualSourceFeatures)
      
      // 清除现有交互
      clearInteractions()
      
      // 确定图标文件扩展名
      let iconExt = '.png'
      if (iconType === 'icon') {
        iconExt = '.gif'
      }
      
      // 创建绘制交互
      const drawInteraction = new Draw({
        source: sourceFeaturesInstance,
        type: 'Point',
        style: new Style({
          image: new Icon({
            src: `/icons/${iconType}${iconExt}`,
            scale: scale.value,
            anchor: [0.5, 0.5]
          })
        })
      })
      
      // 添加绘制交互
      mapInstance.addInteraction(drawInteraction)
      interactions.draw = drawInteraction
      
      // 添加事件监听
      drawInteraction.on('drawend', (evt) => {
        const feature = evt.feature
        feature.set('type', 'icon')
        feature.set('iconType', iconType)
        feature.set('iconSrc', `/icons/${iconType}${iconExt}`)
        
        // 设置图标样式
        feature.setStyle(
          new Style({
            image: new Icon({
              src: `/icons/${iconType}${iconExt}`,
              scale: scale.value,
              anchor: [0.5, 0.5]
            })
          })
        )
        
        // 添加到图标数组
        iconFeatureArr.value.push(feature)
        
        console.log('图标已添加:', feature)
        
        // 绘制完成后自动清除交互
        clearInteractions()
        isIconDrawing.value = false
      })
      
      // 添加取消绘制事件监听
      drawInteraction.on('drawabort', () => {
        console.log('图标绘制已取消')
        clearInteractions()
        isIconDrawing.value = false
      })
      
      console.log('图标绘制交互已初始化')
    } catch (error) {
      console.error('初始化图标绘制交互失败:', error)
      isIconDrawing.value = false
      throw error
    }
  }
  
  /**
   * 调整图标大小
   * @param {Number} delta - 缩放变化量
   */
  function adjustIconScale(delta) {
    try {
      // 确保iconFeatureArr已初始化
      if (!iconFeatureArr.value) {
        iconFeatureArr.value = [];
      }
      
      scale.value += delta;
      
      // 防止缩放过小
      if (scale.value < 0.02) {
        scale.value = 0.02;
      }
      
      console.log(`调整图标大小，当前比例: ${scale.value}`);
      
      // 只在有图标要素时更新
      if (iconFeatureArr.value.length > 0) {
        // 更新所有图标的大小
        iconFeatureArr.value.forEach((feature) => {
          if (feature && typeof feature.setStyle === 'function') {
            const iconSrc = feature.get('iconSrc');
            if (iconSrc) {
              feature.setStyle(
                new Style({
                  image: new Icon({
                    src: iconSrc,
                    scale: scale.value
                  })
                })
              );
            }
          }
        });
        
        ElMessage.success(`图标大小已调整为${scale.value.toFixed(2)}`);
      } else {
        console.log('没有可调整的图标');
      }
    } catch (error) {
      console.error('调整图标大小失败:', error);
      ElMessage.error('调整图标大小失败，请查看控制台日志');
    }
  }
  
  /**
   * 保存绘制数据到本地存储
   */
  function saveDrawings() {
    try {
      const sourceFeaturesInstance = unref(actualSourceFeatures);
      
      if (!sourceFeaturesInstance) {
        console.error('数据源未初始化');
        ElMessage.error('数据源未初始化，无法保存');
        return { success: false };
      }
      
      const features = sourceFeaturesInstance.getFeatures();
      console.log(`保存${features.length}个绘制要素`);
      
      // 初始化不同类型的要素数组
      const pointFeatures = [];
      const lineFeatures = [];
      const polygonFeatures = [];
      const circleFeatures = [];
      
      // 遍历分类要素
      features.forEach((feature) => {
        const geometry = feature.getGeometry();
        if (!geometry) return;
        
        const type = geometry.getType();
        const coordinates = geometry.getCoordinates();
        const properties = feature.getProperties();
        
        // 根据几何类型分类
        if (type === 'Point') {
          pointFeatures.push({ geometry: coordinates, properties });
        } else if (type === 'LineString') {
          lineFeatures.push({ geometry: coordinates, properties });
        } else if (type === 'Polygon') {
          polygonFeatures.push({ geometry: coordinates, properties });
        } else if (type === 'Circle') {
          // 特殊处理圆形，保存中心点和半径
          const center = geometry.getCenter();
          const radius = geometry.getRadius();
          const flatCoordinates = geometry.getFlatCoordinates();
          
          circleFeatures.push({
            geometry: coordinates,
            properties: {
              ...properties,
              geometry: {
                flatCoordinates,
                center,
                radius
              }
            }
          });
        }
      });
      
      // 保存到本地存储
      localStorage.setItem('pointFeatures', JSON.stringify(pointFeatures));
      localStorage.setItem('lineFeatures', JSON.stringify(lineFeatures));
      localStorage.setItem('polygonFeatures', JSON.stringify(polygonFeatures));
      localStorage.setItem('circleFeatures', JSON.stringify(circleFeatures));
      
      console.log('绘制数据已保存到本地存储');
      ElMessage({
        message: '保存成功！',
        type: 'success'
      });
      
      return {
        success: true,
        pointFeatures,
        lineFeatures,
        polygonFeatures,
        circleFeatures
      };
    } catch (error) {
      console.error('保存绘制数据失败:', error);
      ElMessage.error('保存绘制数据失败，请查看控制台日志');
      return { success: false, error: error.message };
    }
  }
  
  /**
   * 从本地存储加载绘制数据
   */
  function loadDrawings() {
    try {
      const sourceFeaturesInstance = unref(actualSourceFeatures);
      
      // 检查数据源是否可用
      if (!sourceFeaturesInstance) {
        console.error('数据源未初始化');
        return { success: false, message: '数据源未初始化，无法加载' };
      }
      
      // 从本地存储获取数据
      const pointFeatures = JSON.parse(localStorage.getItem('pointFeatures') || '[]');
      const lineFeatures = JSON.parse(localStorage.getItem('lineFeatures') || '[]');
      const polygonFeatures = JSON.parse(localStorage.getItem('polygonFeatures') || '[]');
      const circleFeatures = JSON.parse(localStorage.getItem('circleFeatures') || '[]');
      
      const totalFeatures = pointFeatures.length + lineFeatures.length + polygonFeatures.length + circleFeatures.length;
      
      // 如果没有任何要素，直接返回成功但特殊标记
      if (totalFeatures === 0) {
        console.log('本地存储中没有绘制要素');
        return { success: true, featuresCount: 0, noFeatures: true };
      }
      
      console.log(`加载要素: ${pointFeatures.length}个点, ${lineFeatures.length}个线, ${polygonFeatures.length}个面, ${circleFeatures.length}个圆`);
      
      // 清除现有要素 - 只在有要素时清除
      sourceFeaturesInstance.clear();
      iconFeatureArr.value = [];
      
      // 恢复点要素
      const points = pointFeatures.map((point) => {
        try {
          // 检查数据有效性
          if (!point.geometry || !Array.isArray(point.geometry)) {
            console.warn('点数据无效，跳过', point);
            return null;
          }
          
          const feature = new Feature({
            geometry: new Point(point.geometry)
          });
          
          // 如果是图标，设置图标样式
          if (point.properties?.iconSrc) {
            feature.setStyle(
              new Style({
                image: new Icon({
                  src: point.properties.iconSrc,
                  scale: scale.value
                })
              })
            );
            
            feature.set('iconSrc', point.properties.iconSrc);
            iconFeatureArr.value.push(feature);
          }
          
          // 设置属性
          if (point.properties) {
            Object.keys(point.properties).forEach(key => {
              if (key !== 'geometry') {
                feature.set(key, point.properties[key]);
              }
            });
          }
          
          // 添加Cesium兼容属性
          feature.set('olcs_properties', {
            olcs_skip_style_conversion: true,
            olcs_custom_style: true
          });
          
          return feature;
        } catch (e) {
          console.warn('处理点数据时出错，跳过', e);
          return null;
        }
      }).filter(Boolean); // 过滤掉null值
      
      // 恢复线要素
      const lines = lineFeatures.map((line) => {
        try {
          // 检查数据有效性
          if (!line.geometry || !Array.isArray(line.geometry)) {
            console.warn('线数据无效，跳过', line);
            return null;
          }
          
          const feature = new Feature({
            geometry: new LineString(line.geometry)
          });
          
          // 设置属性
          if (line.properties) {
            Object.keys(line.properties).forEach(key => {
              if (key !== 'geometry') {
                feature.set(key, line.properties[key]);
              }
            });
          }
          
          // 添加Cesium兼容属性
          feature.set('olcs_properties', {
            olcs_skip_style_conversion: true,
            olcs_custom_style: true
          });
          
          return feature;
        } catch (e) {
          console.warn('处理线数据时出错，跳过', e);
          return null;
        }
      }).filter(Boolean); // 过滤掉null值
      
      // 恢复面要素
      const polygons = polygonFeatures.map((polygon) => {
        try {
          // 检查数据有效性
          if (!polygon.geometry || !Array.isArray(polygon.geometry)) {
            console.warn('面数据无效，跳过', polygon);
            return null;
          }
          
          const feature = new Feature({
            geometry: new Polygon(polygon.geometry)
          });
          
          // 设置属性
          if (polygon.properties) {
            Object.keys(polygon.properties).forEach(key => {
              if (key !== 'geometry') {
                feature.set(key, polygon.properties[key]);
              }
            });
          }
          
          // 添加Cesium兼容属性
          feature.set('olcs_properties', {
            olcs_skip_style_conversion: true,
            olcs_custom_style: true
          });
          
          return feature;
        } catch (e) {
          console.warn('处理面数据时出错，跳过', e);
          return null;
        }
      }).filter(Boolean); // 过滤掉null值
      
      // 恢复圆要素
      const circles = circleFeatures.map((circle) => {
        try {
          let center, radius;
          
          // 检查数据有效性
          if (!circle.geometry && (!circle.properties || !circle.properties.geometry)) {
            console.warn('圆数据无效，跳过', circle);
            return null;
          }
          
          // 从属性中获取中心点和半径
          if (circle.properties && circle.properties.geometry) {
            const { flatCoordinates } = circle.properties.geometry;
            if (!flatCoordinates || !Array.isArray(flatCoordinates)) {
              console.warn('圆坐标数据无效，跳过', circle);
              return null;
            }
            
            center = [flatCoordinates[0], flatCoordinates[1]];
            radius = Math.sqrt(
              Math.pow(flatCoordinates[0] - flatCoordinates[2], 2) +
              Math.pow(flatCoordinates[1] - flatCoordinates[3], 2)
            );
          } else {
            // 兼容旧数据格式
            center = [circle.geometry[0], circle.geometry[1]];
            radius = 100; // 默认半径
          }
          
          const feature = new Feature({
            geometry: new Circle(center, radius)
          });
          
          // 设置属性
          if (circle.properties) {
            Object.keys(circle.properties).forEach(key => {
              if (key !== 'geometry') {
                feature.set(key, circle.properties[key]);
              }
            });
          }
          
          // 添加Cesium兼容属性
          feature.set('olcs_properties', {
            olcs_skip_style_conversion: true,
            olcs_custom_style: true
          });
          
          return feature;
        } catch (e) {
          console.warn('处理圆数据时出错，跳过', e);
          return null;
        }
      }).filter(Boolean); // 过滤掉null值
      
      // 添加所有要素到数据源 - 仅添加有效要素
      const allFeatures = [...points, ...lines, ...polygons, ...circles];
      
      // 只在有要素时添加
      if (allFeatures.length > 0) {
        sourceFeaturesInstance.addFeatures(allFeatures);
      }
      
      return {
        success: true,
        featuresCount: allFeatures.length
      };
    } catch (error) {
      console.error('加载绘制数据失败:', error);
      return { success: false, error, message: '加载绘制数据失败' };
    }
  }
  
  /**
   * 初始化删除交互
   */
  function initDeleteInteraction() {
    try {
      console.log('useDraw: 开始初始化删除交互');
      
      // 验证地图对象和数据源是否已初始化
      if (!validateMapAndSource()) {
        console.warn('无法初始化删除交互，地图对象或数据源未初始化');
        return;
      }
      
      const mapInstance = unref(actualMap);
      const sourceFeaturesInstance = unref(actualSourceFeatures);
      
      // 清除所有现有交互
      clearInteractions();
      
      // 重置所有状态
      isDrawing.value = false;
      isDelete.value = true;
      isModify.value = false;
      isIconDrawing.value = false; // 确保关闭图标绘制状态
      
      // 使用ol-ext的Delete交互
      const deleteInteraction = new Delete({
        source: sourceFeaturesInstance
      });
      
      mapInstance.addInteraction(deleteInteraction);
      interactions.delete = deleteInteraction;
      
      // 添加事件监听
      deleteInteraction.on('delete', (evt) => {
        console.log('已删除要素:', evt.features);
        
        // 从图标数组中移除已删除的图标
        const deletedFeatures = evt.features.getArray();
        const remainingIcons = iconFeatureArr.value.filter(icon => !deletedFeatures.includes(icon));
        if (remainingIcons.length < iconFeatureArr.value.length) {
          console.log(`已从图标数组中移除${iconFeatureArr.value.length - remainingIcons.length}个图标`);
          iconFeatureArr.value = remainingIcons;
        }
      });
      
      console.log('删除交互已初始化，状态:', {
        'isDelete': isDelete.value,
        'isModify': isModify.value,
        'isDrawing': isDrawing.value,
        'isIconDrawing': isIconDrawing.value
      });
    } catch (error) {
      console.error('初始化删除交互失败:', error);
      isDelete.value = false;
    }
  }
  
  /**
   * 初始化编辑交互
   */
  function initModifyInteraction() {
    try {
      console.log('useDraw: 开始初始化编辑交互');
      
      // 验证地图对象和数据源是否已初始化
      if (!validateMapAndSource()) {
        console.warn('无法初始化编辑交互，地图对象或数据源未初始化');
        return;
      }
      
      const mapInstance = unref(actualMap);
      const sourceFeaturesInstance = unref(actualSourceFeatures);
      
      // 清除所有现有交互
      clearInteractions();
      
      // 重置所有状态
      isDrawing.value = false;
      isDelete.value = false;
      isModify.value = true;
      isIconDrawing.value = false; // 确保关闭图标绘制状态
      
      // 创建选择交互
      const select = new Select();
      mapInstance.addInteraction(select);
      interactions.select = select;
      
      // 创建修改交互
      const modify = new Modify({
        features: select.getFeatures()
      });
      mapInstance.addInteraction(modify);
      interactions.modify = modify;
      
      // 添加事件监听
      modify.on('modifyend', (evt) => {
        console.log('要素已修改:', evt.features.getArray());
      });
      
      console.log('编辑交互已初始化，状态:', {
        'isDelete': isDelete.value,
        'isModify': isModify.value,
        'isDrawing': isDrawing.value,
        'isIconDrawing': isIconDrawing.value
      });
    } catch (error) {
      console.error('初始化编辑交互失败:', error);
      isModify.value = false;
    }
  }
  
  /**
   * 初始化所有交互
   */
  function initInteractions() {
    try {
      // 验证地图对象和数据源是否已初始化
      if (!validateMapAndSource()) {
        console.warn('无法初始化交互，地图对象或数据源未初始化');
        return;
      }
      
      // 初始化编辑交互
      initModifyInteraction();
      isModify.value = true;
      
      // 初始化删除交互
      if (isDelete.value) {
        initDeleteInteraction();
      }
      
      console.log('所有交互已初始化');
    } catch (error) {
      console.error('初始化交互失败:', error);
    }
  }
  
  /**
   * 清除所有交互
   */
  function clearInteractions() {
    try {
      // 验证地图对象和数据源是否已初始化
      if (!validateMapAndSource()) {
        console.warn('无法清除交互，地图对象或数据源未初始化');
        return;
      }
      
      const mapInstance = unref(actualMap);
      
      // 清除绘图交互
      clearDrawInteraction();
      
      // 清除删除交互
      if (interactions.delete) {
        try {
          mapInstance.removeInteraction(interactions.delete);
        } catch (e) {
          console.error('清除删除交互失败:', e);
        }
        interactions.delete = null;
      }
      
      // 清除修改交互
      if (interactions.modify) {
        try {
          mapInstance.removeInteraction(interactions.modify);
        } catch (e) {
          console.error('清除修改交互失败:', e);
        }
        interactions.modify = null;
      }
      
      // 清除选择交互
      if (interactions.select) {
        try {
          mapInstance.removeInteraction(interactions.select);
        } catch (e) {
          console.error('清除选择交互失败:', e);
        }
        interactions.select = null;
      }
      
      // 清除绘制交互
      if (interactions.draw) {
        try {
          mapInstance.removeInteraction(interactions.draw);
        } catch (e) {
          console.error('清除绘制交互失败:', e);
        }
        interactions.draw = null;
      }
      
      // 重置所有状态
      isDrawing.value = false;
      isIconDrawing.value = false;
      isDelete.value = false;
      isModify.value = false;
      
      console.log('所有交互已清除，所有状态已重置:', {
        'isDrawing': isDrawing.value,
        'isIconDrawing': isIconDrawing.value,
        'isDelete': isDelete.value,
        'isModify': isModify.value
      });
    } catch (error) {
      console.error('清除交互失败:', error);
    }
  }
  
  const startDrawIcon = async (iconType) => {
    try {
      // 关闭其他状态
      isDrawing.value = false
      isDelete.value = false
      isModify.value = false
      
      // 如果已经在绘制图标，则清除
      if (isIconDrawing.value) {
        clearDrawInteraction()
        isIconDrawing.value = false
        return
      }
      
      // 设置图标绘制状态
      isIconDrawing.value = true
      
      // 添加图标
      await addIcon(iconType)
      
      console.log('图标绘制状态:', {
        isIconDrawing: isIconDrawing.value,
        isDrawing: isDrawing.value,
        isDelete: isDelete.value,
        isModify: isModify.value
      })
    } catch (error) {
      console.error('绘制图标失败:', error)
      isIconDrawing.value = false
    }
  }
  
  // 返回暴露的方法和状态
  return {
    // 状态
    isDrawing,
    isIconDrawing,
    isDelete,
    isModify,
    selectedShape,
    selectedIcon,
    scale,
    shapeOptions,
    iconOptions,
    iconFeatureArr,
    
    // 方法
    drawShape,
    startDrawIcon,
    adjustIconScale,
    initDeleteInteraction,
    initModifyInteraction,
    clearDrawInteraction,
    saveDrawings,
    loadDrawings,
    initInteractions,
    clearInteractions
  };
} 
